import { Injectable } from '@nestjs/common';
import {InjectQueue} from "@nestjs/bull";
import {type Queue} from "bull";
import { SendEmailRequest, SendEmailResponse } from '@libs/common/protos/email/email';
import { ConfigService } from '@nestjs/config';



@Injectable()
export class MicroEmailService {
  constructor(
      @InjectQueue('smtp') private readonly smtpQueue: Queue,
      private configService: ConfigService,
  ) {
    console.log('Redis 配置:', {
      host: this.configService.get('REDIS_HOST'),
      port: this.configService.get('REDIS_PORT'),
      password: this.configService.get('REDIS_PASSWORD') || '无密码',
    });

    // 打印邮件配置
    console.log('邮件服务配置:', {
      host: this.configService.get('MAIL_HOST'),
      port: 465,
      user: this.configService.get('MAIL_USER'),
      from: this.configService.get('MAIL_FROM'),
    });
  }

  async checkRedisConnection() {
    try {
      console.log('尝试连接 Redis...');
      // 测试 Redis 连接（Bull 内部通过 Redis 客户端实现）
      await this.smtpQueue.client.ping();
      console.log('Redis 连接正常');
    } catch (error) {
      console.error('Redis 连接失败:', error); // 打印具体错误
    }
  }


  async sendWelcomeEmail(data: SendEmailRequest) {
    console.log('2',data)
    await this.checkRedisConnection();

    const job = await this.smtpQueue.add('welcome', { data });
    return { success: true, message: 'Email sent successfully', jobId: job.id } as SendEmailResponse;
  }

  async sendResetPasswordEmail(data: SendEmailRequest) {
    const job = await this.smtpQueue.add('reset-password', { data });
    return   { success: true,message: 'Email sent successfully',jobId: job.id } as SendEmailResponse;
  }
}
